package com.icongyou.enterprise.talent_analysis.service.impl;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.icongyou.enterprise.common.exception.BusinessException;
import com.icongyou.enterprise.talent_analysis.entity.DimensionDetail;
import com.icongyou.enterprise.talent_analysis.entity.PortraitCache;
import com.icongyou.enterprise.talent_analysis.entity.PortraitResponse;
import com.icongyou.enterprise.talent_analysis.mapper.PortraitCacheMapper;
import com.icongyou.enterprise.talent_analysis.service.PortraitCacheService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

@Slf4j
@Service
@RequiredArgsConstructor
public class PortraitCacheServiceImpl implements PortraitCacheService {

    private final PortraitCacheMapper cacheMapper;
    private final ObjectMapper objectMapper;

    @Override
    public PortraitResponse getFromCache(String studentId, String templateId) {
        PortraitCache cache = cacheMapper.selectByStudentAndTemplate(studentId, templateId);
        if (cache == null) {
            return null;
        }
        
        try {
            PortraitResponse response = new PortraitResponse();
            response.setLabels(objectMapper.readValue(cache.getLabelsJson(), new TypeReference<List<String>>() {}));
            response.setScores(objectMapper.readValue(cache.getScoresJson(), new TypeReference<List<Double>>() {}));
            response.setDimensions(objectMapper.readValue(cache.getDimensionsJson(), new TypeReference<List<DimensionDetail>>() {}));
            response.setAiUsed(cache.getAiUsed());
            response.setGeneratedAt(cache.getGeneratedAt().atZone(java.time.ZoneId.systemDefault()).toInstant().toEpochMilli());
            
            return response;
            
        } catch (Exception e) {
            return null;
        }
    }

    @Override
    @Async
    public void asyncUpdateCache(String studentId, String templateId, PortraitResponse response) {
        try {
            // 检查是否已存在
            PortraitCache existing = cacheMapper.selectByStudentAndTemplate(studentId, templateId);
            
            if (existing != null) {
                // 更新
                existing.setLabelsJson(objectMapper.writeValueAsString(response.getLabels()));
                existing.setScoresJson(objectMapper.writeValueAsString(response.getScores()));
                existing.setDimensionsJson(objectMapper.writeValueAsString(response.getDimensions()));
                existing.setAiUsed(response.isAiUsed());
                existing.setUpdatedAt(LocalDateTime.now());
                cacheMapper.updateByIdWithVersion(existing);
            } else {
                // 插入
                PortraitCache cache = new PortraitCache();
                cache.setId(UUID.randomUUID().toString());
                cache.setStudentId(studentId);
                cache.setTemplateId(templateId);
                cache.setLabelsJson(objectMapper.writeValueAsString(response.getLabels()));
                cache.setScoresJson(objectMapper.writeValueAsString(response.getScores()));
                cache.setDimensionsJson(objectMapper.writeValueAsString(response.getDimensions()));
                cache.setAiUsed(response.isAiUsed());
                cache.setGeneratedAt(LocalDateTime.now());
                cache.setUpdatedAt(LocalDateTime.now());
                cache.setVersion(0);
                cacheMapper.insert(cache);
            }
        } catch (Exception e) {
        }
    }
    
    @Override
    public void invalidateTemplateCache(String templateId) {
        try {
            int count = cacheMapper.deleteByTemplateId(templateId);
        } catch (Exception e) {
            log.error("清除模板缓存失败 - templateId: {}", templateId, e);
        }
    }
}
